class LayeredMonitoring {
    constructor() {
        this.comparisonChart = null;
        this.trendChart = null;
        this.currentTimeRange = '24h';
        
        // 等待 DOM 加载完成后再初始化
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.initialize());
        } else {
            this.initialize();
        }
    }

    initialize() {
        this.initializeCharts();
        this.initializeEventListeners();
        this.updateData();
        this.startRealTimeUpdate();
    }

    initializeCharts() {
        // 初始化分层对比图
        const comparisonCtx = document.getElementById('layerComparisonChart');
        if (comparisonCtx) {
            this.comparisonChart = new Chart(comparisonCtx.getContext('2d'), {
                type: 'bar',
                data: {
                    labels: ['表层 (0-10cm)', '中层 (10-20cm)', '深层 (20-30cm)'],
                    datasets: [{
                        label: '土壤墒情 (%)',
                        data: [],
                        backgroundColor: [
                            'rgba(24, 144, 255, 0.6)',
                            'rgba(82, 196, 26, 0.6)',
                            'rgba(250, 173, 20, 0.6)'
                        ],
                        borderColor: [
                            'rgba(24, 144, 255, 1)',
                            'rgba(82, 196, 26, 1)',
                            'rgba(250, 173, 20, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100
                        }
                    }
                }
            });
        }

        // 初始化分层趋势图
        const trendCtx = document.getElementById('layerTrendChart');
        if (trendCtx) {
            this.trendChart = new Chart(trendCtx.getContext('2d'), {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [
                        {
                            label: '表层',
                            data: [],
                            borderColor: 'rgba(24, 144, 255, 1)',
                            backgroundColor: 'rgba(24, 144, 255, 0.1)',
                            tension: 0.4
                        },
                        {
                            label: '中层',
                            data: [],
                            borderColor: 'rgba(82, 196, 26, 1)',
                            backgroundColor: 'rgba(82, 196, 26, 0.1)',
                            tension: 0.4
                        },
                        {
                            label: '深层',
                            data: [],
                            borderColor: 'rgba(250, 173, 20, 1)',
                            backgroundColor: 'rgba(250, 173, 20, 0.1)',
                            tension: 0.4
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100
                        }
                    },
                    plugins: {
                        tooltip: {
                            mode: 'index',
                            intersect: false
                        }
                    }
                }
            });
        }
    }

    initializeEventListeners() {
        // 区域选择事件
        document.getElementById('layer-area-selector').addEventListener('change', (e) => {
            this.updateMonitoringPoints(e.target.value);
            this.updateData();
        });

        // 监测点选择事件
        document.getElementById('layer-point-selector').addEventListener('change', () => {
            this.updateData();
        });

        // 时间范围按钮点击事件
        document.querySelectorAll('.time-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                document.querySelectorAll('.time-btn').forEach(b => b.classList.remove('active'));
                btn.classList.add('active');
                this.currentTimeRange = btn.dataset.range;
                this.updateData();
            });
        });

        // 导出按钮点击事件
        document.querySelector('.export-btn').addEventListener('click', () => {
            this.exportData();
        });
    }

    updateMonitoringPoints(areaId) {
        const pointSelector = document.getElementById('layer-point-selector');
        pointSelector.innerHTML = '<option value="all">所有监测点</option>';
        
        if (areaId !== 'all') {
            const pointCount = 12;
            for (let i = 1; i <= pointCount; i++) {
                pointSelector.innerHTML += `<option value="point${i}">监测点${i}</option>`;
            }
        }
    }

    generateTimeLabels() {
        const labels = [];
        const now = new Date();
        let interval, count;

        switch (this.currentTimeRange) {
            case '24h':
                interval = 3600000; // 1小时
                count = 24;
                break;
            case '7d':
                interval = 86400000; // 1天
                count = 7;
                break;
            case '30d':
                interval = 86400000; // 1天
                count = 30;
                break;
            default:
                interval = 3600000;
                count = 24;
        }

        for (let i = count - 1; i >= 0; i--) {
            const time = new Date(now - i * interval);
            labels.push(this.formatTime(time));
        }

        return labels;
    }

    formatTime(date) {
        if (this.currentTimeRange === '24h') {
            return `${date.getHours()}:00`;
        } else {
            return `${date.getMonth() + 1}/${date.getDate()}`;
        }
    }

    generateMockData(count) {
        return Array.from({length: count}, () => ({
            surface: 20 + Math.random() * 30,
            middle: 25 + Math.random() * 30,
            deep: 15 + Math.random() * 30
        }));
    }

    updateData() {
        // 更新概览数据
        this.updateOverview();

        // 更新分层对比图
        const comparisonData = this.generateMockData(1)[0];
        this.updateComparisonChart([
            comparisonData.surface,
            comparisonData.middle,
            comparisonData.deep
        ]);

        // 更新趋势图
        const trendData = this.generateMockData(
            this.currentTimeRange === '24h' ? 24 :
            this.currentTimeRange === '7d' ? 7 : 30
        );
        this.updateTrendChart(trendData);

        // 更新数据表格
        this.updateDataTable();
    }

    updateOverview() {
        document.getElementById('surface-moisture').textContent = 
            (20 + Math.random() * 30).toFixed(1);
        document.getElementById('middle-moisture').textContent = 
            (25 + Math.random() * 30).toFixed(1);
        document.getElementById('deep-moisture').textContent = 
            (15 + Math.random() * 30).toFixed(1);
    }

    updateComparisonChart(data) {
        this.comparisonChart.data.datasets[0].data = data;
        this.comparisonChart.update();
    }

    updateTrendChart(data) {
        const labels = this.generateTimeLabels();
        this.trendChart.data.labels = labels;
        this.trendChart.data.datasets[0].data = data.map(d => d.surface);
        this.trendChart.data.datasets[1].data = data.map(d => d.middle);
        this.trendChart.data.datasets[2].data = data.map(d => d.deep);
        this.trendChart.update();
    }

    updateDataTable() {
        const tbody = document.getElementById('layer-data-body');
        const mockData = this.generateMockTableData();
        
        tbody.innerHTML = mockData.map(record => `
            <tr>
                <td>${record.time}</td>
                <td>${record.area}</td>
                <td>${record.point}</td>
                <td>${record.surface}%</td>
                <td>${record.middle}%</td>
                <td>${record.deep}%</td>
                <td>
                    <span class="status-tag ${record.status.class}">
                        ${record.status.text}
                    </span>
                </td>
            </tr>
        `).join('');
    }

    generateMockTableData() {
        const records = [];
        const areaId = document.getElementById('layer-area-selector').value;
        const pointId = document.getElementById('layer-point-selector').value;
        
        for (let i = 0; i < 10; i++) {
            const surface = (20 + Math.random() * 30).toFixed(1);
            const middle = (25 + Math.random() * 30).toFixed(1);
            const deep = (15 + Math.random() * 30).toFixed(1);
            
            records.push({
                time: new Date(Date.now() - i * 3600000).toLocaleString(),
                area: areaId === 'all' ? `区域${Math.ceil(Math.random() * 5)}` : areaId.replace('area', '区域'),
                point: pointId === 'all' ? `监测点${Math.ceil(Math.random() * 12)}` : pointId.replace('point', '监测点'),
                surface,
                middle,
                deep,
                status: this.getLayerStatus(surface, middle, deep)
            });
        }
        
        return records;
    }

    getLayerStatus(surface, middle, deep) {
        const avg = (parseFloat(surface) + parseFloat(middle) + parseFloat(deep)) / 3;
        
        if (avg < 20) {
            return { text: '偏干', class: 'danger' };
        } else if (avg > 40) {
            return { text: '偏湿', class: 'warning' };
        }
        return { text: '适宜', class: 'normal' };
    }

    startRealTimeUpdate() {
        // 每30秒更新一次数据
        setInterval(() => {
            this.updateData();
        }, 30000);
    }

    exportData() {
        // 模拟导出功能
        alert('数据导出功能即将上线');
    }
}

// 创建实例
window.layeredMonitoring = new LayeredMonitoring(); 